import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {SystemService} from "../system.service";
import {StorageService} from "../../services/storage.service";
import {FormBuilder} from "@angular/forms";
import {ConfirmationService} from "primeng/primeng";

@Component({
  selector: 'app-cognate-role',
  templateUrl: './cognate-role.component.html',
  styleUrls: ['./cognate-role.component.css']
})
export class CognateRoleComponent implements OnInit {
  display;
  title;
  @Output() closeCognateRole =new EventEmitter();
  @Output() cognateRole = new EventEmitter(); //保存关联角色
  @Input() currentPid;
  @Input() state;
  tableDatas: any;                   // 角色表格数据
  selectedRoles = [];//选中的角色

  constructor(
    private systemService: SystemService,
    private storageService: StorageService,
    private fb: FormBuilder,
    private confirmationService: ConfirmationService
  ) { }

  ngOnInit() {
    this.display = true;
    this.systemService.getPerRoles(this.currentPid.pid).subscribe(data => {
      if(this.state == 'cognate'){//关联角色
        this.title = this.currentPid.name + '关联角色';
        this.tableDatas = data;
        //选中已拥有的角色
        for(let i = 0;i < data.length;i++){
          if(data[i].checked){
            this.selectedRoles.push(data[i])
          }
        }
      }else {//查看角色
        this.title = this.currentPid.name + '角色';
        //只显示已拥有的角色
        let dataFilters = [];
        for(let i = 0;i < data.length;i++){
          if(data[i].checked){
            dataFilters.push(data[i])
          }
        }
        this.tableDatas = dataFilters;
      }
    })
  }

  //确定
  formSubmit(bool){
    this.systemService.saveCognateRoles(this.selectedRoles, this.currentPid.pid).subscribe(()=>{
      this.cognateRole.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }

  closeCogRoleMask(bool){
    this.closeCognateRole.emit(bool);
  }

}
